#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <map>
using namespace std;

class Solution {
	vector<int> father, sec;

	int find(int x)
	{
		return father[x] == x ? x : father[x] = find(father[x]);
	}

	void merge(int x, int y)
	{
		int fx = find(x);
		int fy = find(y);
		if (fx != fy) {
			father[fx] = fy;
			sec[fy] |= sec[fx];
		}
	}

    public:
	vector<int> findAllPeople(int n, vector<vector<int>> &meetings, int firstPerson)
	{
		father.resize(n);
                sec.resize(n);
		iota(father.begin(), father.end(), 0);
		//ranges::fill(father, 0);
		fill(sec.begin(), sec.end(), 0);
		father[firstPerson] = 0;
		sec[0] = 1;
		sort(meetings.begin(), meetings.end(), [](auto &a, auto &b) { return a[2] < b[2]; });

		int m = meetings.size();
		for (int i = 0, s = 0, t = meetings[0][2], a, b; i < m; i++) {
			a = meetings[i][0];
			b = meetings[i][1];
			if (meetings[i][2] == t) {
				merge(a, b);
			} else {
				for (; s < i; s++) {
					a = meetings[s][0];
					b = meetings[s][1];
                                        if(!sec[find(a)]){
                                                father[a] = a;
                                        }
                                        if(!sec[find(b)]){
                                                father[b] = b;
                                        }
				}
                                t = meetings[i][2];
                                i--;
			}
		}

                vector<int> ans;
                for(int i = 0; i < n; i++){
                        if(sec[find(i)]){
                                ans.push_back(i);
                        }
                }

                return ans;
	}
};

int main()
{
	int n = 12, firstPerson = 9;
	vector<vector<int>> meetings = {{10,8,6},{9,5,11},{0,5,18},{4,5,13},{11,6,17},{0,11,10},{10,11,7},{5,8,3},{7,6,16},{3,6,10},{3,11,1},{8,3,2},{5,0,7},{3,8,20},{11,0,20},{8,3,4},{1,9,4},{10,7,11},{8,10,18}};
	vector<int> seq = Solution().findAllPeople(n, meetings, firstPerson);
        for(auto v : seq){
                cout<<v<<" ";
        }
        cout<<endl;
	return 0;
}